import api from "./utils/axios";
import { user, token } from "./store/user";
import { navigate } from "svelte-routing";
import { toast } from "@zerodevx/svelte-toast";
import { encryptAESDefault } from "./utils/aes.util";
import { writable, derived, get } from "svelte/store";
import { todos } from "./store/todo";

export const register = (username, password) =>
  api.post("/auth/register", { username, password });
export const loading = writable(false);
export const error = writable(null);

// 加载待办事项
export async function loadTodos() {
  if (!get(user)) return;
  loading.set(true);
  error.set(null);
  try {
    const res = await api.get("/todos");
    todos.set(res.data);
  } catch (err) {
    error.set(err.message || "加载失败");
  } finally {
    loading.set(false);
  }
}

// 添加新待办事项
export const addTodo = async function (text) {
  if (!text.trim()) return;
  try {
    const res = await api.post("/todos", { text, done: false });
    todos.update((items) => [res.data, ...items]);
  } catch (err) {
    error.set(err.message || "添加失败");
  }
};

// 删除待办
export const deleteTodo = async function (id) {
  try {
    await deleteTodoAPI(id);
    todos.update((items) => items.filter((item) => item.id !== id));
  } catch (err) {
    error.set(err.message || "删除失败");
  }
};

// 切换完成状态
export const toggleDone = async function (id, currentDone) {
  try {
    await updateTodoAPI(id, { done: !currentDone });
    todos.update((items) =>
      items.map((item) =>
        item.id === id ? { ...item, done: !currentDone } : item
      )
    );
  } catch (err) {
    error.set(err.message || "更新失败");
  }
};

// 更新待办事项状态
export const updateTodoAPI = (id, data) => api.put(`/todos/${id}`, data);
// 删除待办事项
export const deleteTodoAPI = (id) => api.delete(`/todos/${id}`);
// 获取单个待办事项
export const getTodoById = (id) => api.get(`/todos/${id}`);
export const login = async function (username, password) {
  // 实际项目中应该调用API验证
  let userId = 0;
  const res = await api.post("/auth/login", {
    username: encryptAESDefault(username),
    password: encryptAESDefault(password),
  });
  if (res.code === 200) {
    const resUser = res.data.data;
    userId = resUser.userId;
    user.set({ username: resUser.username, role: resUser.role, userId });
    token.set(res.data.token);
    toast.push(res.message);
    navigate("/");
  } else {
    toast.push(res.message);
  }
  return false;
};

// logout, /auth/logout
export const logout = async function () {
  try {
    const res = await api.get("/auth/logout");
    if (res.code === 200) {
      user.set(null);
      token.set(null);
      localStorage.removeItem("user");
      localStorage.removeItem("token");
      navigate("/login");
      toast.push(res.message);
    } else {
      toast.push(res.message);
    }
  } catch (err) {
    console.error("Logout error:", err);
    let errMsg = "网络错误，请重试";
    if (err.response?.data?.message) {
      errMsg = err.response.data.message; // 后端返回的错误信息
    } else if (err.message) {
      errMsg = err.message; // Axios 错误信息
    }
    toast.push(errMsg);
  }
  return false;
};
export default api;
